﻿using System;
using System.Text;
using Newtonsoft.Json;
using RabbitMQ.Client;
namespace ConsoleAppFramework.Rmq
{
    public class RmqMessageProducer
    {
        public static void MessageSend<T>(RmqUrlEnum rmqUrlEnum, string exchange, string routeKey, T message, RmqMessageProps props = null)
        {
            using IModel model = RmqConnectPoolFactory.GetClientPool(rmqUrlEnum).GetConnect().GetChannel();
            IBasicProperties basicProperties = model.CreateBasicProperties();
            SetProps(basicProperties, props);
            string s = JsonConvert.SerializeObject(message);
            model.BasicPublish(exchange, routeKey, mandatory: false, basicProperties, Encoding.UTF8.GetBytes(s));
        }

        private static void SetProps(IBasicProperties props, RmqMessageProps messageProps)
        {
            if (messageProps == null)
            {
                messageProps = new RmqMessageProps();
            }

            if (!string.IsNullOrEmpty(messageProps.CorrelationId))
            {
                props.CorrelationId = messageProps.CorrelationId;
            }

            if (!string.IsNullOrEmpty(messageProps.UserId))
            {
                props.UserId = messageProps.UserId;
            }

            if (!string.IsNullOrEmpty(messageProps.MessageId))
            {
                props.MessageId = messageProps.MessageId;
            }

            if (messageProps.Headers != null)
            {
                props.Headers = messageProps.Headers;
            }

            if (messageProps.Expiration.HasValue)
            {
                props.Expiration = messageProps.Expiration.ToString();
            }

            if (messageProps.DeliveryMode.HasValue)
            {
                props.DeliveryMode = Convert.ToByte(messageProps.DeliveryMode);
            }

            props.Priority = (byte)messageProps.Priority;
        }
    }
}
